package com.leadiv.ann.matrix;

/**
 * A utility class to convert boolean to bipolar and bipolar to boolean
 * @author leadiv
 */
public class BiPolarUtil {
    /**
     * Returns a bipolar from a boolean. Converts the boolean to an int and then
     * makes the conversion
     * @param b a boolean value
     * @return 1 for true and -1 for false
     */
    public static double bipolar2double(final boolean b) { 
        return (2*(b ? 1 : 0)) - 1;
    }

    /**
     * Returns an array of bipolar values from boolean values.
     * @param b an array of boolean value (true|false)
     * @return an array of bipolar values (1|-1)
     */
    public static double[] bipolar2double(final boolean b[]) {
        int i;
        double[] a1dResult = new double[b.length];
        int len = b.length;

        for( i=0; i<len; i++ ) {
            a1dResult[i] = BiPolarUtil.bipolar2double(b[i]);
        }

        return a1dResult;
    }

    /**
     * Returns a 2D array of bipolar values from boolean values
     * @param b 2D array of boolean values (true|false)
     * @return an 2D array of bipolar values (1|-1)
     */
    public static double[][] bipolar2double(final boolean a2b[][]) {
        int iR, iC;
        int iRow = a2b.length;
        int iCol = a2b[0].length;
        double[][] a2dResult = new double[iRow][iCol];

        for( iR = 0; iR < iRow; iR++ ) {
            for( iC = 0; iC < iCol; iC++ ) {
                a2dResult[iR][iC] = BiPolarUtil.bipolar2double(a2b[iR][iC]);
            }
        }

        return a2dResult;
    }

    /**
     * Returns a boolean from an bipolar value
     * @param d bipolar value (1|-1)
     * @return a boolean value (true|false)
     */
    public static boolean double2bipolar(final double d) {
        return ((d + 1) / 2 == 1) ? true : false;
    }

    /**
     * Returns an array of boolean values from bipolar values.
     * @param d an array of bipolar values (1|-1)
     * @return an array of boolean values (true|false)
     */
    public static boolean[] double2bipolar(final double a1d[]) {
        int i;
        boolean[] a1bResult = new boolean[a1d.length];
        int len = a1d.length;

        for( i=0; i<len; i++ ) {
            a1bResult[i] = BiPolarUtil.double2bipolar(a1d[i]);
        }

        return a1bResult;
    }

    /**
     * Returns a 2D array of boolean values from bipolar values
     * @param b 2D array of bipolar values (1|-1)
     * @return an 2D array of boolean values (true|false)
     */
    public static boolean[][] double2bipolar(final double a2d[][]) {
        int iRow = a2d.length;
        int iCol = a2d[0].length;
        int iR, iC;
        boolean[][] a2bResult = new boolean[iRow][iCol];

        for( iR=0; iR<iRow; iR++ ) {
            for( iC=0; iC<iCol; iC++ ) {
                a2bResult[iR][iC] = BiPolarUtil.double2bipolar(a2d[iR][iC]);
            }
        }

        return a2bResult;
    }
}